package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springmvc 提供的拦截器
 * 1.编写一个类，实现handlerInterceptor
 * 2.配置拦截器，拦截路径/*
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录（看session中有没有employee），如果登录就放行
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");
        if (employeeId!=null){
            BaseContext.set(employeeId);
            return true;
        }
        if (userId!=null){
            BaseContext.set(userId);
            return true;
        }

        //表示用户没有登录，告诉前端，本次请求访问未登录，被拒绝处理，响应code=0，msg=NOTLOGIN
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;
    }
      //最终通知,该方法执行后移除数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        BaseContext.remove();
    }
}



